package repository

import (
	"goscan-mgt/model"
	"goscan-mgt/utils"

	"gorm.io/gorm"
)

// ScanResultRepository 结构体定义了与扫描结果表交互的仓库
type ScanResultRepository struct {
	DB *gorm.DB // 数据库连接
}

// NewScanResultRepository 创建一个新的ScanResultRepository实例
func NewScanResultRepository() *ScanResultRepository {
	db := utils.GetDB() // 获取数据库连接
	return &ScanResultRepository{DB: db}
}

// Create 创建新的扫描结果记录
func (repo *ScanResultRepository) Create(scanResult *model.ScanResult) error {
	return repo.DB.Create(scanResult).Error
}

// GetByID 根据ID获取扫描结果记录
func (repo *ScanResultRepository) GetByID(id uint) (*model.ScanResult, error) {
	var scanResult model.ScanResult
	err := repo.DB.First(&scanResult, id).Error
	return &scanResult, err
}

// Update 更新扫描结果记录
func (repo *ScanResultRepository) Update(scanResult *model.ScanResult) error {
	return repo.DB.Save(scanResult).Error
}

// Delete 根据ID删除扫描结果记录
func (repo *ScanResultRepository) Delete(id uint) error {
	return repo.DB.Delete(&model.ScanResult{}, id).Error
}

// GetAll 获取所有扫描结果记录
func (repo *ScanResultRepository) GetAll() ([]model.ScanResult, error) {
	var scanResults []model.ScanResult
	err := repo.DB.Find(&scanResults).Error
	return scanResults, err
}

// GetPaginated 获取分页扫描结果列表
func (repo *ScanResultRepository) GetPaginated(page int, pageSize int) (*utils.Pagination[model.ScanResult], error) {
	dbModel := repo.DB.Model(&model.ScanResult{}).Order("id desc")
	result, err := utils.NewPagination[model.ScanResult](page, pageSize, dbModel)
	return result, err
}

// GetPaginatedByProjectID 根据项目ID获取分页扫描结果
func (repo *ScanResultRepository) GetPaginatedByProjectID(page int, pageSize int, projectID uint) (*utils.Pagination[model.ScanResult], error) {
	dbModel := repo.DB.Model(&model.ScanResult{}).Order("id desc").Where("project_id = ?", projectID)
	result, err := utils.NewPagination[model.ScanResult](page, pageSize, dbModel)
	return result, err
}
